<template>
  <el-dialog
    class="public-dialog"
    title="修改报关信息"
    width="500"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div>
      <el-form
        ref="formRef"
        label-position="top"
        label-width="100px"
        :model="form"
      >
        <el-form-item label="项号">
          <!-- <el-input v-model="form.xno" placeholder="请选择项号" /> -->
          <el-select
            v-model="form.xno"
            placeholder="请选择项号"
            @change="handleXno"
            class="w-full"
          >
            <el-option
              v-for="item in optionsData.xnosOpt"
              :key="item.xno"
              :label="item.xno"
              :value="item.xno"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="海关编码">
          <el-input v-model="form.etc_hs_code" placeholder="请输入海关编码" />
        </el-form-item>
        <el-form-item label="报关品名">
          <el-input
            v-model="form.etc_declare_goods_name"
            placeholder="请输入报关品名"
          />
        </el-form-item>
        <el-form-item label="报关单位">
          <el-input
            v-model="form.etc_declare_unit"
            placeholder="请输入报关单位"
          />
        </el-form-item>
        <el-form-item label="报关数量">
          <el-input-number
            v-model="form.etc_declare_nums"
            :controls="false"
            class="w-full"
            placeholder="请输入报关数量"
          />
        </el-form-item>
        <el-form-item label="报关单价">
          <el-input-number
            v-model="form.etc_declare_price"
            :controls="false"
            placeholder="请输入报关单价"
            :precision="4"
            class="w-full"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="报关币别">
          <!-- <el-input
            v-model="form.etc_declare_currency"
            placeholder="请输入报关币别"
          /> -->
          <el-select
            v-model="form.etc_declare_currency"
            placeholder="请选择报关币别"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              :label="item.label"
              :value="item.label"
              v-for="item in optionsData?.currency || []"
              :key="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="报关总额">
          <el-input-number
            v-model="form.etc_declare_total_amount"
            :controls="false"
            :precision="4"
            :min="0"
            class="w-full"
            disabled
            placeholder="请输入报关总额"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? "关闭" : "取消" }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus";
import { declareCompanyEtc, getXnos } from "../../api/index.js";
import { tipMessage } from "@/hooks/tool.js";
import { getCurrency } from "@/api/public.js";
const props = defineProps({
  data: { type: Object, default: () => {} },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
});
const { data } = toRefs(props);
const form = reactive({
  id: null,
  etc_hs_code: null,
  etc_declare_goods_name: null,
  etc_declare_unit: null,
  etc_declare_nums: null,
  etc_declare_price: null,
  etc_declare_currency: null,
  etc_declare_total_amount: null,
  xno: null,
});
let isInitialized = false; // 标记是否是首次加载
watch(
  () => data.value,
  (val) => {
    if (val) {
      for (let key in form) {
        form[key] = val[key];
      }
      nextTick(() => {
        isInitialized = true;
      });
      getCurrencyList();
      getXnosList(form.id);
    }
  }
);

watch(
  () => [form.etc_declare_nums, form.etc_declare_price],
  ([nums, price]) => {
    if (!isInitialized) return;
    if (nums !== null && price !== null) {
      form.etc_declare_total_amount = nums * price;
    }
  },
  { deep: true }
);
const emit = defineEmits(["update:modelValue", "refresh", "close"]);

const formRef = ref();
const loading = ref();
const submit = () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate((valid) => {
      const _model = JSON.parse(JSON.stringify(form));
      if (valid) {
        resolve(_model);
      } else {
        reject(false);
      }
    });
  });
};
const optionsData = reactive({});
const getCurrencyList = async () => {
  const { data } = await getCurrency();
  optionsData.currency = data || [];
};

const getXnosList = async (id) => {
  const { data } = await getXnos({ id });
  optionsData.xnosOpt = data || [];
};

const handleXno = (val) => {
  let obj = optionsData?.xnosOpt?.find((item) => item.xno == val);
  console.log(obj);
  for (let key in form) {
     if (key === 'id') continue;
    form[key] = obj[key];
  }
};

const handleSave = async () => {
  try {
    const formInfo = await submit();
    const { code, message, data } = await declareCompanyEtc(formInfo);
    if (code !== 200) {
      ElMessage.warning(message);
      return;
    }
    ElMessage.success("修改成功");
    handleClose(true);
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning("请检查表单信息");
    }
    console.error(e);
  } finally {
    loading.value = false;
  }
};

const handleClose = async (refresh) => {
  for (let key in form) {
    form[key] = null;
  }
  isInitialized = false;
  await nextTick();
  formRef.value.resetFields();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
